package org.android.bbdroid;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import org.android.bbdroid.guiutils.Alerts;
import org.android.bbdroid.webservice.PHPBBClient;
import org.android.bbdroid.webservice.data.TopicForum;
import org.android.bbdroid.webservice.data.TopicInfo;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class BBDroidSubmitPostTopicActivity extends Activity implements
		View.OnClickListener {
	private TopicForum forum;
	private TopicInfo topic;

	public void onClick(View paramView) {
		EditText teMessage = (EditText) findViewById(org.android.bbdroid.R.id.teMessage);
		if (TextUtils.isEmpty(teMessage.getText())) {
			Alerts.w(this, org.android.bbdroid.R.string.warning_text,
					org.android.bbdroid.R.string.empty_message_text);
			return;
		}

		EditText teSubject = (EditText) findViewById(org.android.bbdroid.R.id.teSubject);
		if (getIntent().getAction().equals(BBDroidActions.ADD_POST)) {

			final ProgressDialog dlg=Alerts.prog(this, "", 
					getString(org.android.bbdroid.R.string.loading_text), true);
			
			
			new AsyncTask<Object, Void, Boolean>(){

				@Override
				protected Boolean doInBackground(Object... params) {
					String location=getLocationName();
					PHPBBClient client = PHPBBClient.getInstance();
					StringBuilder builder=new StringBuilder();
					builder.append("\n\n----------------------------\n");
					builder.append("Inviato con BBDroid dal mio "+android.os.Build.MODEL+"\n");
					if(location!=null)
						builder.append("Da "+location);
					return client.postReply((TopicInfo)params[0], (String)params[1], (String)params[2] + builder.toString());
				}
				
				@Override
				protected void onPostExecute(Boolean result){
					dlg.dismiss();
					if(!result){
						Alerts.w(BBDroidSubmitPostTopicActivity.this, 
								org.android.bbdroid.R.string.error_text,
								org.android.bbdroid.R.string.postreply_error_text);
						return;
					}
					Toast.makeText(BBDroidSubmitPostTopicActivity.this,
							org.android.bbdroid.R.string.message_sent_text,
							Toast.LENGTH_LONG).show();
					finish();
				}
				
			}
			.execute(this.topic, teSubject.getText().toString(),
					teMessage.getText().toString());
	
		} else {
			if (TextUtils.isEmpty(teSubject.getText())) {
				Alerts.w(this, org.android.bbdroid.R.string.warning_text,
						org.android.bbdroid.R.string.empty_title_text);
				return;
			}
			
			final ProgressDialog dlg=Alerts.prog(this, "", 
					getString(org.android.bbdroid.R.string.loading_text), true);
			
			new AsyncTask<Object, Void, Boolean>(){

				@Override
				protected Boolean doInBackground(Object... params) {
					PHPBBClient client = PHPBBClient.getInstance();
					return client.createTopic((TopicForum)params[0], (String)params[1], (String)params[2]);
				}
				
				@Override
				protected void onPostExecute(Boolean result){
					dlg.dismiss();
					if(!result){
						Alerts.w(BBDroidSubmitPostTopicActivity.this, org.android.bbdroid.R.string.error_text,
								org.android.bbdroid.R.string.createtopic_error_text);
						return;
					}
					Toast.makeText(BBDroidSubmitPostTopicActivity.this,
							org.android.bbdroid.R.string.topic_created_text,
							Toast.LENGTH_LONG).show();
					finish();
				}
			}
			.execute(this.forum, teSubject.getText().toString(),
					teMessage.getText().toString());
					
		}
	}

	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(org.android.bbdroid.R.layout.new_post_topic);
		TextView tvSubject = (TextView) findViewById(org.android.bbdroid.R.id.tvSubject);
		Button sendButton = (Button) findViewById(org.android.bbdroid.R.id.sendMessageButton);
		sendButton.setOnClickListener(this);
		
		if (getIntent().getAction().equals(BBDroidActions.ADD_POST)) {
			this.topic = ((TopicInfo) getIntent().getExtras().getSerializable(
					"topic"));
			setTitle(getString(org.android.bbdroid.R.string.reply_to_text)
					+ " " + this.topic.getTitle());
			((EditText) findViewById(org.android.bbdroid.R.id.teSubject))
					.setText("Re: " + this.topic.getTitle());
			sendButton
					.setText(getString(org.android.bbdroid.R.string.send_message_text));
			tvSubject
					.setText(getString(org.android.bbdroid.R.string.subject_text));

		} else if (getIntent().getAction().equals(BBDroidActions.ADD_TOPIC)) {
			
			this.forum = ((TopicForum) getIntent().getExtras().getSerializable(
					"forum"));
			setTitle(getString(org.android.bbdroid.R.string.create_topic_text));
			sendButton
					.setText(getString(org.android.bbdroid.R.string.submit_topic_text));
			tvSubject
					.setText(getString(org.android.bbdroid.R.string.topic_title_text));

		} else
			throw new RuntimeException("Cannot handle action "
					+ getIntent().getAction());
	}

	protected Dialog onCreateDialog(int paramInt, Bundle paramBundle) {
		return Alerts.onCreateDialog(this, paramInt, paramBundle);
	}
	
	private String getLocationName(){
		LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

		String provider = locationManager.getBestProvider(new Criteria(), true);
		Location locations = locationManager.getLastKnownLocation(provider);
		if(null!=locations ){                 
		double longitude = locations.getLongitude();
		double latitude = locations.getLatitude();
		Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());                 
		try {
		    List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
		    if(null!=listAddresses&&listAddresses.size()>0){
		        return listAddresses.get(0).getLocality();//getAddressLine(1);
		    }
		} catch (IOException e) {
		    e.printStackTrace();
		}

		}
		return null;
	}
}